const { logger } = require("ee-core/log");
const os = require('os');
const DesCrypto = require("../../utils/DesCrypto.js");

class BaseHardware {
    cryptoKey = "4F420A92-6FD3-4644-ACB2-60A786B21979";
    async getCPUId() {
        //return "BFEBFBFF000306A9"
    }

    getMacAddresses() {
        //return [];
    }

    async getDiskSerialNumber() {
        //return "625B89ABK0L5";
    }



    // 获取所有 IPv4 网卡详细信息
    async getNetworkDetails() {
        [{
            "ip": "192.168.18.32",
            "interface": "以太网 2",
            "mac": "ac:22:0b:dc:d0:d0",
            "gateway": "192.168.18.254",
            "gatewayMac": "44-00-4d-65-cb-44",
            "description": "Realtek PCIe GbE Family Controller"
        }];
    }

    //获取网络卡驱动
    async networkCardDrive() {
        [{
            "name": "10",
            "ServiceName": "{ABA0566B-EECB-4BD7-81F0-93EB4AF65997}",
            "Description": "Realtek USB GbE Family Controller"
        },
        {
            "name": "11",
            "ServiceName": "{50BA1E68-C8AA-43EC-8EB1-04002EAEBFB7}",
            "Description": "Realtek PCIe GbE Family Controller"
        }]
    }

    getComputerName() {
        //新版登录的计算机名后面加个5
        let rawName = os.hostname();
        let result = "G" + rawName.substring(1);
        return result.replace(".local", ""); // 去除 .local 后缀
    }
    formatMac(mac) {
        // 将MAC地址统一格式化为12位大写字符串，确保每个部分都有两位数字
        return mac
            .toLowerCase()
            .split(/[:\-]/)
            .map(part => part.padStart(2, '0'))
            .join('')
            .toUpperCase();
    }
    // 获取所需硬件信息(明文)
    async getHardInfoToString() {
        try {
            const cpuId = await this.getCPUId();
            const diskSerial = await this.getDiskSerialNumber();
            const networkDetails = await this.getNetworkDetails();

            const fingerprints = networkDetails.map((nicInfo) => {
                const formattedMac = this.formatMac(nicInfo.mac);
                const formattedGatewayMac = this.formatMac(nicInfo.gatewayMac);

                let result = `CPU:${cpuId};NC:${formattedMac};HD:${diskSerial}@${nicInfo.gateway}^${formattedGatewayMac}`;
                logger.info("HardInfoString:"+result);
                return result;
            });

            const fullString = fingerprints.join("$");

            // 获取计算机名
            const computerName = this.getComputerName()
            return `0010000000|${computerName}|${DesCrypto.encrypt(fullString, this.cryptoKey)}`;
        } catch (error) {
            return "";
        }
    }



    //注册
    async getRegComputerUrl(userid, pwd, errMsg) {

        let code = "10000"
        const regex = /^([\u4e00-\u9fa5，]+)（(\d+)）$/;
        const match = errMsg.match(regex);
        if (match) {
            errMsg = match[1];    // "未授权电脑，已授权网络环境"
            code = match[2];    // "10001"
        }
        let cpuId = await this.getCPUId();
        logger.info(cpuId, DesCrypto.encrypt(cpuId, this.cryptoKey))
        cpuId = encodeURI(DesCrypto.encrypt(cpuId, this.cryptoKey));
        cpuId = encodeURI(cpuId);
        const computerName = encodeURI(this.getComputerName())
        let diskSerial = await this.getDiskSerialNumber();
        diskSerial = encodeURI(DesCrypto.encrypt(await this.getDiskSerialNumber(), this.cryptoKey));
        const md5pwd = DesCrypto.md5(pwd);
        errMsg = encodeURI(errMsg)

        const networkDetails = await this.getNetworkDetails();

        let fNclist = [];
        for (let i = 0; i < networkDetails.length; i++) {
            const nicInfo = networkDetails[i];
            const formattedMac = this.formatMac(nicInfo.mac);
            const formattedGatewayMac = this.formatMac(nicInfo.gatewayMac);
            const regNetworkCards = await this.networkCardDrive();
            const regNetworkCard = regNetworkCards.find(item => {
                return item.Description == nicInfo.description
            }) || { Description: "", ServiceName: "" }
            const description = regNetworkCard.Description;
            const serviceName = regNetworkCard.ServiceName;
            const nc = `Name:${serviceName};Description:${description};Mac:${formattedMac};IP:${nicInfo.ip};Gateway:${nicInfo.gateway};GateMac:${formattedGatewayMac}`;
            logger.info("hardInfo:", nc)
            fNclist.push(DesCrypto.encrypt(nc, this.cryptoKey))
        }

        let url = `http://softmanager.fdauto.com:8182/computerreg/toRegPage.do?userid=${userid}&pcname=${computerName}&hd=${diskSerial}&cpuid=${cpuId}&regcode=${code}&password=${md5pwd}&errmsg=${errMsg}&nclist=${fNclist.join("&nclist=")}`;

        console.log(url)

        return url
    }

        //注册
    async getRegComputerUrl2() {

        const networkDetails = await this.getNetworkDetails();

        let fNclist = [];
        for (let i = 0; i < networkDetails.length; i++) {
            const nicInfo = networkDetails[i];
            const formattedMac = this.formatMac(nicInfo.mac);
            const formattedGatewayMac = this.formatMac(nicInfo.gatewayMac);
            const regNetworkCards = await this.networkCardDrive();
            const regNetworkCard = regNetworkCards.find(item => {
                return item.Description == nicInfo.description
            }) || { Description: "", ServiceName: "" }
            const description = regNetworkCard.Description;
            const serviceName = regNetworkCard.ServiceName;
            const nc = `Name:${serviceName};Description:${description};Mac:${formattedMac};IP:${nicInfo.ip};Gateway:${nicInfo.gateway};GateMac:${formattedGatewayMac}`;
            logger.info("hardInfo:", nc)
            fNclist.push(nc)
        }

        return fNclist
    }

}



module.exports = BaseHardware;

//let computerService = new ComputerService()
//computerService.getRegComputerUrl("01521", "1521..", "未授权电脑，已授权网络环境（10001）").then(res => { console.log(res) })
//computerService.readNetworkCards();

